package com.fingard.dsp.bank.directbank.hxb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.directbank.gdrc01.util.Tool;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;

import java.io.File;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Parker on 2019-08-07.
 * @version 1.0
 */
public class HXB01Receipt extends HXB01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        //电子回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt, retAts);
                } else {
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    retAts.respCode = "-1";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void download(ReqQryReceipt p_reqReceipt, RetAtsReceipt retAts) {
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

            int tmpFileCount = 0;//上传回单数量
            StringBuilder json = new StringBuilder();
            if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
            } else {
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }

            String templatePath = getBankConfig().getValueAsString("templetFile");
            String receiptFile = getBankConfig().getValueAsString("receiptFile");

            //按日循环
            while (tmpIntFrom <= tmpIntTo) {
                //交易代码#交易账号#开始日期#截至日期#起始交易金额#截至交易金额#@@@@
                String sendInfo = MessageFormat.format("{0}#{1}#{2}#{3}#{4}#{5}@@@@", "xhj5003", p_reqReceipt.actNum, tmpIntFrom + "", tmpIntFrom + "", getBankConfig().getValueAsString("MinAmount"), getBankConfig().getValueAsString("MaxAmount"));
                String[] tmpStrRet = sendToBank(sendInfo);
                if (tmpStrRet[0].length() == 0) {
                    String[] resultArr = tmpStrRet[1].split("#");
                    if (resultArr[0].equals("000000")) {
                        //int i = Integer.parseInt(resultArr[1]);
                        for (int i = 2; i < resultArr.length - 1; i++) {
                            //付款人的名|账号|开户行|金额|用途|收款人户名|收款人账号|开户行|验证码|记账日期|流水号|借贷标记（备注:1:出账，2：入账）|电子回单专用章|
                            String[] detailArr = resultArr[i].split("\\|");
                            Random random = new Random();
                            int randomInt = random.nextInt(99);
                            String randomStr = String.format("%02d", randomInt);
                            String receiptFileName = p_reqReceipt.actNum + "_" + Format.Date8Format.format(tmpCalendarFrom.getTime())
                                    + "_" + detailArr[10] + randomStr + ".pdf";
                            Map<String, String> formInfoMap = new ConcurrentHashMap<String, String>();
                            formInfoMap.put("PayerName", detailArr[0]);
                            formInfoMap.put("PayerNum", detailArr[1]);
                            formInfoMap.put("PayBank", detailArr[2]);
                            formInfoMap.put("Amount", detailArr[3] + "元");
                            formInfoMap.put("UpAmount", Tool.change(Double.parseDouble(detailArr[3])));//大写金额
                            formInfoMap.put("Purpose", detailArr[4]);
                            formInfoMap.put("RecName", detailArr[5]);
                            formInfoMap.put("RecNum", detailArr[6]);
                            formInfoMap.put("RecBank", detailArr[7]);
                            formInfoMap.put("CheckCode", detailArr[8]);
                            formInfoMap.put("TranDate", detailArr[9]);
                            formInfoMap.put("TranSeqNo", detailArr[10]);
                            formInfoMap.put("MoneyWay", detailArr[11]);
                            formInfoMap.put("PrintDate", Format.Date10Format.format(new Date()));
                            //回单编号   日期+流水号
                            formInfoMap.put("ReceiptCode", Format.Date8Format.format(Format.Date10Format.parse(detailArr[9])) + detailArr[10] + randomStr);
                            String newPDFPath = receiptFile + receiptFileName;

                            if (FileHelper.existFile(newPDFPath) || "true".equals(PdfGenerateUtil.fillTemplate(templatePath, newPDFPath, formInfoMap))) {
                                //生成PDF文件成功,上传文件到共享目录下
                                String ftpFilePath = "";
                                String AtsFilePath = "";
                                int result = -1;
                                String tmpByDate = Format.Date8Format.format(new Date());
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                        + p_reqReceipt.reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                        result = FileHelper.copyFile(newPDFPath, shareDir + tmpByDate + receiptFileName);
                                        AtsFilePath = tmpByDate + receiptFileName;//回单文件仓库存储路径
                                    } else {
                                        if (new File(newPDFPath).exists()) {
                                            WriteBankLogLn(
                                                    "正在上传文件至共享目录:" + tmpByDate + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(newPDFPath, tmpByDate,
                                                    FGBiz.dspCenter.dspSet.receiptShareDir);
                                            AtsFilePath = tmpByDate + new File(newPDFPath).getName();//回单文件仓库存储路径
                                        }
                                    }
                                } else {
                                    //ftp服务器
                                    FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                    WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                    AtsFilePath = tmpByDate + new File(newPDFPath).getName();//回单文件仓库存储路径
                                    //上传ftp服务器的地址
                                    ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                    WriteBankLogLn("开始将回单" + newPDFPath + "上传至" + ftpFilePath);
                                    //上传至ftp
                                    result = FtpUtil.ftpUploading(ftpSet3, newPDFPath, ftpFilePath);
                                }


                                if (result == 0 || result == 1) {
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                        tmpFileCount++;
                                    } else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    // 推送数据给ATS处理
                                    json.append("{");
                                    json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                    json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                    json.append("\"receiptCode\":\"" + formInfoMap.get("ReceiptCode") + "\",");
                                    json.append("\"receiptType\":\"" + "" + "\",");
                                    json.append("\"receiptState\":\"" + "" + "\",");
                                    String oppActNum = "";
                                    if (p_reqReceipt.actNum.equals(formInfoMap.get("RecNum"))) {
                                        json.append("\"oppActName\":\"" + formInfoMap.get("PayerName") + "\",");
                                        json.append("\"oppActNum\":\"" + formInfoMap.get("PayerNum") + "\",");
                                        json.append("\"moneyway\":\"" + "2" + "\",");
                                        oppActNum = formInfoMap.get("PayerNum");
                                    } else {
                                        json.append("\"oppActName\":\"" + formInfoMap.get("RecName") + "\",");
                                        json.append("\"oppActNum\":\"" + formInfoMap.get("RecNum") + "\",");
                                        json.append("\"moneyway\":\"" + "1" + "\",");
                                        oppActNum = formInfoMap.get("RecNum");
                                    }
                                    json.append("\"amount\":\"" + formInfoMap.get("Amount").replace("元", "") + "\",");
                                    //ATSES-24144 dsp华夏银行电子回单补充任务规则
                                    String transDate = Format.Date10Format.format(tmpCalendarFrom.getTime());
                                    json.append("\"tranSeqNo\":\"" + DateHelper.convertD10toD8(transDate) + p_reqReceipt.actNum + oppActNum+ "\",");
                                    //json.append("\"bnkSeqNo\":\"" + transDate + p_reqReceipt.actNum + oppActNum + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");
                                    json.append("\"tranDate\":\"" + transDate + "\",");
                                    json.append("\"filePath\":\"" + AtsFilePath + "\",");
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                } else {
                                    WriteBankLogLn(tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                    retAts.respCode = "-1";
                                    retAts.respInfo = tmpIntFrom + ":上传文件至共享目录失败，请检查共享目录配置是否正确";
                                }
                            } else {
                                WriteBankLogLn("生成PDF电子回单文件失败, PDF电子回单文件不存在");
                                retAts.respCode = "-1";
                                retAts.respInfo = "生成PDF电子回单文件失败, PDF电子回单文件不存在";
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = convertRespToBank(resultArr[0]);//获取银行返回信息"查询失败，银行返回码："+resultArr[0]
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            }

            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");

            json.append("]}");
            if (tmpFileCount > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "成功保存文件条数为0，不需要推送数据到ATS";
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }

        } catch (Exception e) {
            WriteBankLogLn(e.getMessage());
            e.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
        }
    }
}